import fs from 'fs-extra';
import path from 'path';
import { default as ssim } from "image-ssim";
import jpeg from 'jpeg-js';
import { PNG } from 'pngjs';
import { decodeTga } from '@lunapaint/tga-codec';

export async function loadImage(file: string): Promise<ssim.IImage | null> {
    const ext = path.extname(file).toLowerCase();
    const content = await fs.readFile(file);
    if (ext == '.png') {
        try {
            const png = await PNG.sync.read(content);
            return { width: png.width, height: png.height, data: png.data, channels: 4 };
        } catch(e) {
            console.error('load png failed:', file);
            console.error(e);
        }
    }
    if (ext == '.jpg') {
        const jpg = jpeg.decode(content);
        return { width: jpg.width, height: jpg.height, data: jpg.data, channels: 3 };
    }
    if (ext == '.tga') {
        const tga = await decodeTga(content);
        return { ...tga.image, channels: 4 };
    }
    return null;
}